<template>
  <van-header title="登录/注册" left-arrow :right-icon="false"></van-header>
  <div class="section">
    <van-form @submit="handleSubmit">
      <van-field
        v-model="formData.phone"
        name="phone"
        label="+86"
        placeholder="请输入手机号"
        :rules="[{ pattern, message: '请输入正确的手机号' }]"
      />
      <van-field v-model="formData.captcha" name="captcha" placeholder="请输入验证码">
        <template #button>
          <span @click="handleGetCode">发送验证码</span>
        </template>
      </van-field>
      <div class="btns">
        <van-button round block type="primary" :disabled="disabled" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import VanHeader from '@/components/header/Header.vue';
import { useMyStores } from '@/store';
import { useMyRouters } from '@/router';
import { isEmpty } from '../../util';
import { login, captchaSent } from '../../api/wangyi/login';
import { Toast } from 'vant';

const { appStore } = useMyStores();
const { router } = useMyRouters();

const pattern = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
let formData = reactive({
  phone: '',
  captcha: ''
});
const disabled = ref(true);

// 获取验证码
const handleGetCode = () => {
  captchaSent(formData.phone)
    .then(res => {
      console.log(res);
      Toast('验证码已发送')
    })
    .catch(err => {
      console.log(err);
    });
};

const handleSubmit = values => {
  console.log('submit', values);
  login(values)
    .then(res => {
      console.log(res);
      if (res.code == 200) {
        appStore.SET_LOGIN(true);
        appStore.SET_USERINFO(res);
        router.back();
      }
    })
    .catch(err => {
      console.log(err);
    });
};

watch(
  () => formData.captcha,
  newVal => {
    if (!isEmpty(newVal)) {
      disabled.value = false;
    } else {
      disabled.value = true;
    }
  }
);
</script>

<style lang="less" scoped>
.section {
  padding: 12px;
}
.van-form {
  // margin-top: 120px;
  :deep(.van-field__label) {
    width: auto;
  }
  :deep(.van-field__button) {
    color: #1989fa;
    &:active {
      opacity: 0.7;
    }
  }
  .btns {
    button {
      margin-top: 10px;
      letter-spacing: 10px;
    }
  }
}
</style>
